package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.Mail;
import com.fsd.core.util.ParametersUtil;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_leaveword;
import com.fsd.admin.model.F_flowdealt;
import com.fsd.admin.model.F_flowrecord;
import com.fsd.admin.model.Z_ysqgk;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.Z_ysqgkService;
import com.fsd.admin.dao.Z_ysqgkDao;
import com.fsd.admin.entity.A_LoginInfo;
import com.google.gson.Gson;

@Repository("z_ysqgkServiceImpl")
public class Z_ysqgkServiceImpl extends WorkFlowServiceImpl<Z_ysqgk, String> implements Z_ysqgkService{
    
    private static final Logger log = Logger.getLogger(Z_ysqgkServiceImpl.class);
    private String depict = "依申请公开";
    
    @Resource(name = "z_ysqgkDaoImpl")
	public void setBaseDao(Z_ysqgkDao Z_ysqgkDao) {
		super.setBaseDao(Z_ysqgkDao);
	}
	
	@Resource(name = "z_ysqgkDaoImpl")
	private Z_ysqgkDao objectDao;

    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;

	/**
     * 流程编码
     */
	public static final String flowCode = "ysqgk";
	
	
	/**
	 * 退回到流程申请人调用
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowBackOriginal(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 撤回到流程申请人调用
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowRecallOriginal(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 开始流程调用数据对象处理
	 * @param dataobjectid
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowStart(String dataobjectid, String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + dataobjectid + "'");
	}
	
	/**
	 * 终止流程调用数据对象处理
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowStop(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 完成流程调用数据对象处理
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowFinish(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 保存当前流程节点数据对象处理
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowNodeDealt(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 自动流程节点数据对象处理
	 * @param record
	 * @param dealt
	 * @param term
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public boolean saveWorkFlowNodeAuto(F_flowrecord record, F_flowdealt dealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update Z_ysqgk t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
		return true;
	}
	
	/**
	 * 自动流程节点数据对象处理
	 * @param record
	 * @param dealt
	 * @param term
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public String saveWorkFlowNodeAutoValue(F_flowrecord record, F_flowdealt dealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		return null;
	}

	/**
	 * 自动流程节点数据选择单一对象处理
	 * @param record
	 * @param dealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @return
	 * @throws Exception
	 */
	public boolean saveWorkFlowNodeAutoChooseSingle(F_flowrecord record, F_flowdealt dealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		Z_ysqgk obj = this.objectDao.get(record.getDataobjectid());
		if (dealt.getValueinfo().equals("FSDDELETE")){
			obj.setDeleted("1");
		}else{
			obj.setAddemployeeid(dealt.getValueinfo());
			obj.setAddemployeename(dealt.getValuedepict());
			obj.setDeleted("0");
			A_Employee empObj = this.employeeService.get(dealt.getValueinfo());
			this.sendMail(obj, empObj);
		}
		obj.setIsreply("false");
		obj.setAuditing("false");
		obj.setFlowstatus(dataStatus);
		obj.setFlowstatusname(dataStatusName);
		this.objectDao.update(obj);
		return true;
	}
	
	/**
	 * 自动流程节点数据选择多对象处理
	 * @param record
	 * @param dealtList
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @return
	 * @throws Exception
	 */
	public boolean saveWorkFlowNodeAutoChooseMulti(F_flowrecord record, List<F_flowdealt> dealtList, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		return true;
	}
	

	private void sendMail(Z_ysqgk obj, A_Employee empObj){
		if(empObj.getEmail() != null && !"".equals(empObj.getEmail())){
			//发送邮件开始
			String smtp = "smtp.qq.com";//SMTP服务器
	    	String from = "1438619547@qq.com";//发信人
	    	String username="1438619547@qq.com";//用户名
	    	String password="gsdlr2015/07/06";//密码
	    	String to = empObj.getEmail();//收信人
	    	String subject = "甘肃省国土资源厅门户网站-受理回复提醒";//邮件主题
	    	//邮件内容
	    	String content = "甘肃省国土资源厅门户网站后台<br />“依申请公开”受理，有您需要处理的回复信息！" +
	    			"<br/><br/>甘肃省国土资源厅门户网站&nbsp;<a target='_blank' href='http://www.gsdlr.gov.cn/admin'>后台登录</a>";
	    	Mail.send(smtp, from, to, subject, content, username, password);
	    	//发送邮件结束
		}
	}
	
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("sqsj"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("querycode") != null && !"".equals(objectMap.get("querycode"))){
				c.add(Restrictions.like("qureycode", "%" + objectMap.get("querycode") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 加载分页数据，加载所属回复人数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListByEmployee(ParametersUtil param, A_LoginInfo loginInfo) throws Exception{
		A_Employee employee = loginInfo.getEmployee();
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("sqsj"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if (!employee.isIsadmin()){
				if(objectMap.get("glqx") != null && !"".equals(objectMap.get("glqx"))){
					if (!this.checkPopedom(objectMap.get("glqx").toString(), Config.POPEDOMMEUN, loginInfo.getPopedomMap())){
						c.add(Restrictions.eq("addemployeeid", employee.getId()));
					}
				}
			}
			if(objectMap.get("querycode") != null && !"".equals(objectMap.get("querycode"))){
				c.add(Restrictions.like("qureycode", "%" + objectMap.get("querycode") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public void save(Z_ysqgk obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_ysqgk old_obj = objectDao.get(obj.getId());
			old_obj.setXm(obj.getXm());
			old_obj.setGzdw(obj.getGzdw());
			old_obj.setZjmc(obj.getZjmc());
			old_obj.setZjhm(obj.getZjhm());
			old_obj.setTxdz(obj.getTxdz());
			old_obj.setYzbm(obj.getYzbm());
			old_obj.setLxdh(obj.getLxdh());
			old_obj.setDzyx1(obj.getDzyx1());
			old_obj.setMc(obj.getMc());
			old_obj.setZzjgdm(obj.getZzjgdm());
			old_obj.setYyzzxx(obj.getYyzzxx());
			old_obj.setFrdb(obj.getFrdb());
			old_obj.setLxrxm(obj.getLxrxm());
			old_obj.setLxrdh(obj.getLxrdh());
			old_obj.setCz(obj.getCz());
			old_obj.setLxdz(obj.getLxdz());
			old_obj.setDzyx2(obj.getDzyx2());
			old_obj.setSqrqm(obj.getSqrqm());
			old_obj.setSxxxnrms(obj.getSxxxnrms());
			old_obj.setSxxxyt(obj.getSxxxyt());
			old_obj.setSxxxsqh(obj.getSxxxsqh());
			old_obj.setQtts(obj.getQtts());
			old_obj.setSfsqjmfy(obj.getSfsqjmfy());
			old_obj.setSxxxzdgyfs(obj.getSxxxzdgyfs());
			old_obj.setHqxxfs(obj.getHqxxfs());
			old_obj.setQtfs(obj.getQtfs());
			old_obj.setQureycode(obj.getQureycode());
			old_obj.setUpdatedate(this.getData());//设置修改日期
			old_obj.setUpdateemployeeid(employee.getId());//设置修改用户id
			old_obj.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			objectDao.update(old_obj);
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			obj.setAuditing("false");//设置审核标志(false:未审核 true：已审核)
			obj.setSelected("false");//设置是否选登(false:不选登 true：选登)
			obj.setSqsj(this.getData());//申请时间
			if(!obj.getAtitle().equals("") && obj.getAtitle() != null){
				obj.setIsreply("true");
			}else{
				obj.setIsreply("false");
			}
			objectDao.save(obj);
		}
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update Z_ysqgk t set t.deleted = '1', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public Z_ysqgk getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_ysqgk obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		
		return obj;
	}
	
	/**
	 * 修改状态
	 * @param parameters
	 */
	public void updateEnabledObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		if (isEnabled)
			objectDao.executeHql("update Z_ysqgk t set t.auditing = 'true' where t.id in (" + ids + ")");
		else
			objectDao.executeHql("update Z_ysqgk t set t.auditing = 'false' where t.id in (" + ids + ")");
	}
	
	/**
	 * 提交回复
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public void saveHuifu(Z_ysqgk obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_ysqgk obj_old = objectDao.get(obj.getId());
			if (obj_old != null){
				obj_old.setAtitle(obj.getAtitle());
				obj_old.setAcontent(obj.getAcontent());
				if (obj_old.getIsreply() != null && obj_old.getIsreply().equals("true")){
					obj_old.setIsreply("true");
					obj_old.setUpdatedate(this.getData());//设置修改日期
					obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
					obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
				}else{
					obj_old.setIsreply("true");
					obj_old.setAbranchid(employee.getBranchid());
					obj_old.setAbranchname(employee.getBranchname());
					obj_old.setAdddate(this.getData());//设置添加日期
					obj_old.setAddemployeeid(employee.getId());//设置添加用户id
					obj_old.setAddemployeename(employee.getRealname());//设置添加用户姓名
				}
				obj_old.setAuditing("false");
				objectDao.update(obj_old);
			}
		}
	}
	

	/**
	 * 加载回收站分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public void saveDealtObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("id", objectMap.get("id")));
		List<Z_ysqgk> objList = objectDao.getList(c);
		if(objList == null || objList.size() == 0){
			throw new BusinessException(depict + "未找到要处理的数据!");
		}
		for (Z_ysqgk obj : objList) {
			if ("true".equals(obj.getIsreply()))
				throw new BusinessException(depict + "数据已回复!");
			if (obj.getAddemployeeid() != null && !"".equals(obj.getAddemployeeid()))
				throw new BusinessException(depict + "数据已有回复人!");
			Map<String, Object> mapJson = new HashMap<String, Object>();
			mapJson.put("data", obj);
			this.saveWorkFlowSubmit(flowCode, obj.getId(), 
					flowCode, "依申请公开", obj.getQureycode(), 
					obj.getSqrqm() + "；" + obj.getXm() + "/" + obj.getMc(), 
					mapJson, employee.getCompanyid(), obj.getSqrqm(), true);
		}
	}
}
